package com.hl.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrosFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //跨域配置:CORS 跨域资源共享
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //设置允许哪些域，可以跨域访问当前的项目,只要写 协议://主机地址:端口     *:允许所有域 要么指定一个域能够访问 要允许所有域都能访问
        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Origin", servletRequest.getRemoteAddr());
        //设置允许的请求方式
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        //设置允许的请求头信息
        response.setHeader("Access-Control-Allow-Headers", "*");
        //是否允许传cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //预检请求的有效期，单位为秒
        response.setHeader("Access-Control-Max-Age", "3600");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
